<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :keyboard="false"
    :forceRender="true"
    v-bind:prefixNo="prefixNo"
    fullscreen
    switchHelp
    switchFullscreen
    @cancel="handleCancel"
    :id="prefixNo"
    style="top: 20px; height: 95%"
  >
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <!-- <a-button v-if="billPrintFlag && isShowPrintBtn" @click="handlePrint('采购订单')">三联打印预览</a-button>
      <a-button v-if="checkFlag && isCanCheck" :loading="confirmLoading" @click="handleOkAndCheck">保存并审核</a-button> -->
      <a-button type="primary" :loading="confirmLoading" @click="handleOk">保存（Ctrl+S）</a-button>
      <!--发起多级审核-->
      <!-- <a-button v-if="!checkFlag" @click="handleWorkflow()" type="primary">提交流程</a-button> -->
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="供应商" data-step="1" data-title="供应商">
              <a-select
                placeholder="请选择供应商"
                v-decorator="['supplierId', validatorRules.supplierId]"
                :dropdownMatchSelectWidth="false"
                showSearch
                optionFilterProp="children"
              >
              
                <a-select-option v-for="(item, index) in supList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="业务员" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                placeholder="请选择业务员"
                showSearch
                optionFilterProp="children"
                v-decorator="['salesmanId', validatorRules.salesmanId]"
              >
                <a-select-option v-for="(item, index) in userList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="单据日期">
              <j-date v-decorator="['operTime', validatorRules.operTime]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="单据编号"
              data-step="2"
              data-title="单据编号"
              data-intro="单据编号自动生成、自动累加、开头是单据类型的首字母缩写，累加的规则是每次打开页面会自动占用一个新的编号"
            >
              <a-input placeholder="请输入单据编号" v-decorator.trim="['orderNo']" />
            </a-form-item>
          </a-col>
           <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="供应商地址">
              <a-input placeholder="请输入供应商地址" v-decorator.trim="['supplierAddress']" />
            </a-form-item>
          </a-col>
        </a-row>
        <j-editable-table
          id="billModal"
          :ref="refKeys[0]"
          :loading="materialTable.loading"
          :columns="materialTable.columns"
          :dataSource="materialTable.dataSource"
          :minWidth="minWidth"
          :maxHeight="300"
          :rowNumber="false"
          :rowSelection="rowCanEdit"
          :actionButton="rowCanEdit"
          :dragSortAndNumber="rowCanEdit"
          @valueChange="onValueChange"
          @added="onAdded"
          @deleted="onDeleted"
        >
          <!-- <template #buttonAfter>
            <a-row v-if="rowCanEdit" :gutter="24" style="float:left;padding-bottom: 5px;" data-step="4" data-title="扫码录入" data-intro="此功能支持扫码枪扫描商品条码进行录入">
              <a-col v-if="scanStatus" :md="6" :sm="24">
                <a-button @click="scanEnter">扫码录入</a-button>
              </a-col>
              <a-col v-if="!scanStatus" :md="16" :sm="24" style="padding: 0 8px 0 12px">
                <a-input placeholder="请扫描商品条码并回车" v-model="scanBarCode" @pressEnter="scanPressEnter" ref="scanBarCode"/>
              </a-col>
              <a-col v-if="!scanStatus" :md="6" :sm="24" style="padding: 0px 12px 0 0">
                <a-button @click="stopScan">收起扫码</a-button>
              </a-col>
            </a-row>
            <a-row :gutter="24" style="float:left;padding-bottom: 5px;">
              <a-col :md="24" :sm="24">
                <a-button style="margin-left: 8px" @click="handleHistoryBillList"><a-icon type="history" />历史单据</a-button>
              </a-col>
            </a-row>
            <a-row v-if="rowCanEdit" :gutter="24" style="float:left;padding-bottom: 5px;padding-left:20px;">
              <a-button icon="import" @click="onImport(prefixNo)">导入明细</a-button>
            </a-row>
          </template> -->
        </j-editable-table>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 } }" label="">
              <a-textarea :rows="1" placeholder="请输入备注" v-decorator="['remark']" style="margin-top: 8px" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="优惠率"
              data-step="5"
              data-title="优惠率"
              data-intro="针对单据明细中商品总金额进行优惠的比例"
            >
              <a-input
                style="width: 80%"
                placeholder="请输入优惠率"
                v-decorator.trim="['discountRate']"
                suffix="%"
                @change="onChangeDiscount"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="付款优惠"
              data-step="6"
              data-title="付款优惠"
              data-intro="针对单据明细中商品总金额进行优惠的金额"
            >
              <a-input
                placeholder="请输入付款优惠"
                v-decorator.trim="['discountAmount']"
                @change="onChangeDiscountMoney"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="优惠后金额"
              data-step="7"
              data-title="优惠后金额"
              data-intro="针对单据明细中商品总金额进行优惠后的金额"
            >
              <a-input placeholder="请输入优惠后金额" v-decorator.trim="['amountAfterDiscount']" :readOnly="true" />
            </a-form-item>
          </a-col>

          <a-col :md="6" :sm="24">
            <a-form-item label="交货方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                placeholder="请选择交货方式"
                showSearch
                optionFilterProp="children"
                v-decorator="['deliveryMethod']"
              >
                <a-select-option v-for="(item, index) in deliveryMethodList" :key="index" :value="item">
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="结算账户"
              data-step="8"
              data-title="结算账户"
              data-intro="如果在下拉框中选择多账户，则可以通过多个结算账户进行结算"
            >
              <a-select
                style="width: 80%"
                placeholder="请选择结算账户"
                v-decorator="['settlementAccountId', validatorRules.accountId]"
                :dropdownMatchSelectWidth="false"
                allowClear
              >
                
                <a-select-option v-for="(item, index) in accountList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
           <a-col :lg="6" :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="物流单号"
              data-step="9"
              data-title="物流单号"
            >
              <a-input
                placeholder="请输入物流单号"
                v-decorator.trim="['logisticsNo']"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="支付金额"
              data-step="9"
              data-title="支付金额"
              data-intro="填写订金之后，在采购入库单会自动计算扣除订金"
            >
              <a-input
                placeholder="请输入支付金额"
                v-decorator.trim="['paidAmount']"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24"> </a-col>
          <a-col :lg="6" :md="12" :sm="24"> </a-col>
        </a-row>
        <!-- <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="附件"
              data-step="10"
              data-title="附件"
              data-intro="可以上传与单据相关的图片、文档，支持多个文件"
            >
              <j-upload v-model="fileList" bizPath="bill"></j-upload>
            </a-form-item>
          </a-col>
        </a-row> -->
      </a-form>
    </a-spin>
    <many-account-modal ref="manyAccountModalForm" @ok="manyAccountModalFormOk"></many-account-modal>
    <import-item-modal ref="importItemModalForm" @ok="importItemModalFormOk"></import-item-modal>
    <vendor-modal ref="vendorModalForm" @ok="vendorModalFormOk"></vendor-modal>
    <account-modal ref="accountModalForm" @ok="accountModalFormOk"></account-modal>
    <link-bill-list ref="linkBillList" @ok="linkBillListOk"></link-bill-list>
    <history-bill-list ref="historyBillListModalForm"></history-bill-list>
    <workflow-iframe ref="modalWorkflow" @ok="workflowModalFormOk"></workflow-iframe>
    <bill-print-iframe ref="modalPrint"></bill-print-iframe>
  </j-modal>
</template>
<script>
import pick from 'lodash.pick'
import ManyAccountModal from '../dialog/ManyAccountModal'
import ImportItemModal from '../dialog/ImportItemModal'
import LinkBillList from '../dialog/LinkBillList'
import VendorModal from '../../system/modules/VendorModal'
import AccountModal from '../../system/modules/AccountModal'
import HistoryBillList from '../dialog/HistoryBillList'
import WorkflowIframe from '@/components/tools/WorkflowIframe'
import BillPrintIframe from '../dialog/BillPrintIframe'
import { FormTypes } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { BillModalMixin } from '../mixins/BillModalMixin'
import { findBillDetailByNumber, getCurrentSystemConfig } from '@/api/api'
import { getMpListShort, changeListFmtMinus, handleIntroJs } from '@/utils/util'
import JUpload from '@/components/jeecg/JUpload'
import JDate from '@/components/jeecg/JDate'
import Vue from 'vue'
export default {
  name: 'PurchaseOrderModal',
  mixins: [JEditableTableMixin, BillModalMixin],
  components: {
    ManyAccountModal,
    ImportItemModal,
    LinkBillList,
    VendorModal,
    AccountModal,
    HistoryBillList,
    WorkflowIframe,
    BillPrintIframe,
    JUpload,
    JDate,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
  },
  data() {
    return {
      ignore:false,
      title: '操作',
      width: '1600px',
      moreStatus: false,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      visible: false,
      supList: [],
      depotList: [],
      operTimeStr: '',
      prefixNo: 'purchase',
      fileList: [],
      rowCanEdit: true,
      //以销定购的场景开关
      purchaseBySaleFlag: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      refKeys: ['materialDataTable'],
      tableKeys: ['materialDataTable'],
      activeKey: 'materialDataTable',
      materialTable: {
        loading: false,
        dataSource: [],
        columns: [
          { title: '', key: 'productId', width: '1%', type: FormTypes.hidden },
          {
            title: '编号',
            key: 'productNo',
            width: '12%',
            type: FormTypes.popupJsh,
            kind: 'material',
            multi: true,
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          { title: '名称', key: 'productName', width: '10%', type: FormTypes.normal },
          { title: '规格型号', key: 'specificationModel', width: '9%', type: FormTypes.normal },
          { title: '品牌', key: 'brand', width: '6%', type: FormTypes.normal },
          // { title: '供应商', key: 'defaultSupplierName', width: '6%', type: FormTypes.normal },
          { title: '库存', key: 'currentStock', width: '5%', type: FormTypes.normal },
          { title: '单位', key: 'unit', width: '4%', type: FormTypes.normal },
          { title: '单价', key: 'unitPrice', width: '5%', type: FormTypes.inputNumber },
          { title: '折扣率', key: 'discountRate', width: '4%', type: FormTypes.inputNumber, placeholder: '%' },
          {
            title: '折扣额',
            key: 'discountAmount',
            width: '5%',
            type: FormTypes.inputNumber,
            readonly: true,
            statistics: true,
          },
          { title: '折后单价', key: 'amountAfterDiscount', width: '5%', type: FormTypes.inputNumber, readonly: true },
          { title: '税率', key: 'taxRate', width: '4%', type: FormTypes.inputNumber, placeholder: '%' },
          {
            title: '税额',
            key: 'taxAmount',
            width: '5%',
            type: FormTypes.inputNumber,
            readonly: true,
            statistics: true,
          },
          { title: '含税单价', key: 'taxInclusivePrice', width: '5%', type: FormTypes.inputNumber, readonly: true },
                    {
            title: '数量',
            key: 'quantity',
            width: '5%',
            type: FormTypes.inputNumber,
            statistics: true,
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '价税合计',
            key: 'priceTaxTotal',
            width: '7%',
            type: FormTypes.inputNumber,
            statistics: true,
            readonly: true,
          },
          { title: '备注', key: 'remark', width: '6%', type: FormTypes.input },
        ],
      },
      confirmLoading: false,
      validatorRules: {
        operTime: {
          rules: [{ required: true, message: '请输入单据日期!' }],
        },
        supplierId: {
          rules: [{ required: true, message: '请选择供应商!' }],
        },
        salesmanId: {
          rules: [{ required: true, message: '请选择业务员!' }],
        },
        accountId: {
          rules: [{ required: true, message: '请选择帐户!' }],
        },
      },
      url: {
        add: '/purchaseOrder',
        edit: '/purchaseOrder/update',
        detailList: '/depotItem/getDetailList',
        importExcelUrl: '/depotItem/importItemExcel',
      },
    }
  },
  created() {},
  methods: {
    //调用完edit()方法之后会自动调用此方法
    editAfter() {
      this.billStatus = '0'
      this.currentSelectDepotId = ''
      this.rowCanEdit = true
      this.materialTable.columns[1].type = FormTypes.popupJsh
      this.changeColumnHide()
      this.changeFormTypes(this.materialTable.columns, 'preNumber', 0)
      this.changeFormTypes(this.materialTable.columns, 'finishNumber', 0)
      if (this.action === 'add') {
        this.addInit(this.prefixNo)
        this.fileList = []
        // this.$nextTick(() => {
        //   handleIntroJs(this.prefixNo, 1)
        //    this.form.setFieldsValue({'discountRate':0,'discountAmount':0,'amountAfterDiscount':0,'paidAmount':0})
        // })
      } else { 
        if (this.model.linkNumber) {
          this.rowCanEdit = false
          this.materialTable.columns[1].type = FormTypes.normal
        }
        this.model.operTime = this.model.orderDate
        // if (this.model.settlementAccountId == null && this.model.accountIdList) {
        //   this.model.accountId = 0
        //   this.manyAccountBtnStatus = true
        //   this.accountIdList = this.model.accountIdList
        //   this.accountMoneyList = this.model.accountMoneyList
        // } else {
        //   this.manyAccountBtnStatus = false
        // }
        //this.fileList = this.model.fileName
        this.$nextTick(() => {
          this.form.setFieldsValue(
            pick(
              this.model,
              'productId',
             'paidAmount',
             'logisticsNo',
             'settlementAccountId',
             'deliveryMethod',
             'amountAfterDiscount',
             'discountAmount',
             'discountRate',
             'remark',
             'orderNo',
             'operTime',
             'supplierAddress',
             'salesmanId',
             'supplierId'
            )
          )
        })
        // // 加载子表数据
        // let params = {
        //   headerId: this.model.id,
        //   mpList: ['制造商', '自定义1'], //扩展属性
        //   linkType: 'basic',
        // }
        // let url = this.readOnly ? this.url.detailList : this.url.detailList
        // this.requestSubTableData(url, params, this.materialTable)
        this.materialTable.dataSource=this.model.purchaseDetailDTOList
        this.materialTable.dataSource.forEach((item, index) => {
          item.unitPrice = item.purchasePrice
        })
      }
      //复制新增单据-初始化单号和日期
      if (this.action === 'copyAdd') {
        this.model.id = ''
        this.model.tenantId = ''
        this.copyAddInit(this.prefixNo)
      }
      this.initDeliveryMethod()
      this.initSupplier(0)
      this.initAccount()
      this.initUser()
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      // let totalPrice = 0
      let billMain = Object.assign(this.model, allValues.formValue)
      let detailArr = allValues.tablesValue[0].values

      for (let item of detailArr) {
        item.purchasePrice = item.unitPrice
      }
      if (this.model.id) {
        billMain.id = this.model.id
      }
      billMain.status = this.billStatus
      billMain.purchaseDetailDTOList=detailArr
      billMain.orderDate= billMain.operTime
      return billMain
    },
    handleHistoryBillList() {
      let organId = this.form.getFieldValue('organId')
      this.$refs.historyBillListModalForm.show('其它', '采购订单', '供应商', organId)
      this.$refs.historyBillListModalForm.disableSubmit = false
    },
    onSearchLinkNumber() {
      this.$refs.linkBillList.purchaseShow('其它', '销售订单', '客户', '1,3', '0,3')
      this.$refs.linkBillList.title = '请选择销售订单'
    },
    onSearchLinkApply() {
      this.$refs.linkBillList.purchaseShow('其它', '请购单', '客户', '1,3')
      this.$refs.linkBillList.title = '请选择请购单'
    },
    linkBillListOk(selectBillDetailRows, linkNumber, organId) {
      this.rowCanEdit = false
      this.materialTable.columns[1].type = FormTypes.normal
      this.changeFormTypes(this.materialTable.columns, 'preNumber', 1)
      this.changeFormTypes(this.materialTable.columns, 'finishNumber', 1)
      if (selectBillDetailRows && selectBillDetailRows.length > 0) {
        let discountLastMoney = 0
        for (let j = 0; j < selectBillDetailRows.length; j++) {
          let info = selectBillDetailRows[j]
          if (info.preNumber) {
            info.operNumber = info.preNumber - info.finishNumber
            info.unitPrice = info.purchaseDecimal
            info.allPrice = (info.operNumber * info.unitPrice).toFixed(2) - 0
            info.taxRate = 0
            info.taxAmount = 0
            info.taxLastMoney = info.allPrice
            discountLastMoney += info.allPrice
          }
          info.linkId = info.id
          this.changeColumnShow(info)
        }
        //根据单号查询单据类型
        findBillDetailByNumber({ number: linkNumber }).then((res) => {
          if (res.code === 200) {
            if (res.data && res.data.subType === '请购单') {
              //关联请购单
              this.$nextTick(() => {
                this.form.setFieldsValue({
                  linkApply: linkNumber,
                })
              })
            } else {
              this.$nextTick(() => {
                this.form.setFieldsValue({
                  linkNumber: linkNumber,
                })
              })
            }
          }
        })
        //给优惠后金额重新赋值
        discountLastMoney = discountLastMoney ? discountLastMoney : 0
        this.$nextTick(() => {
          this.form.setFieldsValue({
            discountLastMoney: discountLastMoney.toFixed(2),
            changeAmount: discountLastMoney.toFixed(2),
          })
        })
        this.materialTable.dataSource = selectBillDetailRows
      }
    },
  },
}
</script>
<style scoped>
</style>